import { defineStore } from 'pinia'
import { chatAPI } from '../api'

export const useChatStore = defineStore('chat', {
    state: () => ({
        currentRole: null,
        currentChatId: null,
        messages: [],
        isLoading: false,
        error: null
    }),

    getters: {
        chatHistory: (state) => state.messages
    },

    actions: {
        setCurrentRole(role) {
            this.currentRole = role
            this.generateChatId()
            this.messages = []
        },

        generateChatId() {
            this.currentChatId = 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        },

        addMessage(message) {
            this.messages.push({
                id: Date.now() + Math.random(),
                ...message,
                timestamp: new Date()
            })
        },

        startChat(message) {
            this.isLoading = true
            this.error = null

            // 添加用户消息
            this.addMessage({
                type: 'user',
                content: message
            })

            // 添加AI消息占位符
            const aiMessageId = Date.now() + Math.random()
            const aiMessage = {
                id: aiMessageId,
                type: 'ai',
                content: '',
                isLoading: true,
                timestamp: new Date()
            }
            this.messages.push(aiMessage)

            return aiMessage
        },

        updateAIMessage(messageId, content) {
            const message = this.messages.find(m => m.id === messageId)
            if (message) {
                // 立即更新内容，实现打字机效果
                message.content += content
            }
        },

        finishAIMessage(messageId) {
            const message = this.messages.find(m => m.id === messageId)
            if (message) {
                message.isLoading = false
            }
            this.isLoading = false
        },

        setError(error) {
            this.error = error
            this.isLoading = false
        },

        clearChat() {
            this.messages = []
            this.generateChatId()
            this.error = null
        }
    }
})
